/*
 *  Copyright (C) 2010 Interactive Media Management
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.i2m.converge.plugins.videooutput;

import dk.i2m.converge.core.content.NewsItem;
import dk.i2m.converge.core.content.NewsItemMediaAttachment;
import dk.i2m.converge.core.security.UserAccount;
import dk.i2m.converge.core.workflow.WorkflowStepAction;
import dk.i2m.converge.core.plugin.WorkflowAction;
import dk.i2m.converge.core.plugin.PluginContext;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Workflow action for outputting a video stream of news items with a given
 * state.
 *
 * @author Allan Lykke Christensen
 */
@dk.i2m.converge.core.annotations.WorkflowAction
public class VideoOutputAction extends WorkflowAction {

    public static final String PROPERTY_OUTPUT_MODE = "output.mode";

    public static final String PROPERTY_OUTPUT_VIDEO_BACKGROUND = "output.video.background";

    public static final String PROPERTY_OUTPUT_VIDEO_SECONDS_PER_STORY = "output.video.seconds_per_story";

    public static final String PROPERTY_OUTPUT_COLLECTION_STATE = "output.state";

    public static final String PROPERTY_OUTPUT_FILE_LOCATION = "output.file.location";

    public static final String PROPERTY_OUTPUT_FILE_FILENAME = "output.file.filename";

    public static final String PROPERTY_OUTPUT_FTP_ADDRESS = "output.ftp.address";

    public static final String PROPERTY_OUTPUT_FTP_PORT = "output.ftp.port";

    public static final String PROPERTY_OUTPUT_FTP_USERNAME = "output.ftp.username";

    public static final String PROPERTY_OUTPUT_FTP_PASSWORD = "output.ftp.password";

    public static final String PROPERTY_OUTPUT_FTP_LOCATION = "output.ftp.location";

    public static final String PROPERTY_OUTPUT_FTP_FILENAME = "output.ftp.filename";

    private static final Logger logger = Logger.getLogger(VideoOutputAction.class.getName());

    private ResourceBundle msgs = ResourceBundle.getBundle("dk.i2m.converge.plugins.videooutput.Messages");

    private Calendar releaseDate = new GregorianCalendar(2010, Calendar.AUGUST, 24, 23, 00);

    private Map<String, String> properties = new HashMap<String, String>();

    private Map<String, String> availableProperties = null;

    @Override
    public void execute(PluginContext ctx, NewsItem item, WorkflowStepAction stepAction, UserAccount user) {

        this.properties = stepAction.getPropertiesAsMap();

        if (!validateProperties()) {
            logger.log(Level.WARNING, "Invalid properties. Cancel execution of {0}", VideoOutputAction.class.getName());
            return;
        }

        Map<String, Object> templateAttributes = new HashMap<String, Object>();
        templateAttributes.put("initiator", user);
        templateAttributes.put("newsitem", item);

        String stateName = this.properties.get(PROPERTY_OUTPUT_COLLECTION_STATE);
        List<NewsItem> items = ctx.findNewsItemsByStateAndOutlet(stateName, item.getOutlet());

        String mode = this.properties.get(PROPERTY_OUTPUT_MODE);

        VideoOutputter api = new VideoOutputter();
        List<VideoNewsItem> videoItems = new ArrayList<VideoNewsItem>();

        for (NewsItem ni : items) {
            String imgUrl = "";
            for (NewsItemMediaAttachment attach : ni.getMediaAttachments()) {
                try {
                    imgUrl = URLEncoder.encode(attach.getMediaItem().getMediaRepository().getWebAccess() + "/" + attach.getMediaItem().getFilename(), "UTF8");
                    break;
                } catch (UnsupportedEncodingException ex) {
                    logger.log(Level.SEVERE, null, ex);
                }
            }

            videoItems.add(new VideoNewsItem(ni.getTitle(), ni.getStory(), imgUrl));
        }


        if ("file".equalsIgnoreCase(mode)) {
            //saveToDisk(outputText);
            api.generate(videoItems, Integer.valueOf(this.properties.get(PROPERTY_OUTPUT_VIDEO_SECONDS_PER_STORY)), this.properties.get(PROPERTY_OUTPUT_VIDEO_BACKGROUND), this.properties.get(PROPERTY_OUTPUT_FILE_LOCATION) + "/" + this.properties.get(PROPERTY_OUTPUT_FILE_FILENAME));
        } else if ("ftp".equalsIgnoreCase(mode)) {
            //sendToFtp(outputText);
        }
    }

    @Override
    public Map<String, String> getAvailableProperties() {
        if (availableProperties == null) {
            availableProperties = new LinkedHashMap<String, String>();
            availableProperties.put("Mode (file/ftp)", PROPERTY_OUTPUT_MODE);
            availableProperties.put("Video background (URL)", PROPERTY_OUTPUT_VIDEO_BACKGROUND);
            availableProperties.put("Seconds per story", PROPERTY_OUTPUT_VIDEO_SECONDS_PER_STORY);
            availableProperties.put("Collection state", PROPERTY_OUTPUT_COLLECTION_STATE);
            availableProperties.put("File mode: Output location", PROPERTY_OUTPUT_FILE_LOCATION);
            availableProperties.put("File mode: Output file name", PROPERTY_OUTPUT_FILE_FILENAME);
            availableProperties.put("FTP mode: Address", PROPERTY_OUTPUT_FTP_ADDRESS);
            availableProperties.put("FTP mode: Port", PROPERTY_OUTPUT_FTP_PORT);
            availableProperties.put("FTP mode: Username", PROPERTY_OUTPUT_FTP_USERNAME);
            availableProperties.put("FTP mode: Password", PROPERTY_OUTPUT_FTP_PASSWORD);
            availableProperties.put("FTP mode: Location", PROPERTY_OUTPUT_FTP_LOCATION);
            availableProperties.put("FTP mode: File name", PROPERTY_OUTPUT_FTP_FILENAME);
        }
        return Collections.unmodifiableMap(availableProperties);
    }

    @Override
    public String getName() {
        return msgs.getString("PLUGIN_NAME");
    }

    @Override
    public String getDescription() {
        return msgs.getString("PLUGIN_DESCRIPTION");
    }

    @Override
    public String getVendor() {
        return msgs.getString("PLUGIN_VENDOR");
    }

    @Override
    public Calendar getDate() {
        return releaseDate;
    }

    /**
     * Validates that sufficient properties has been provided to the plug-in
     * upon execution.
     *
     * @return {@code true} if sufficient properties has been provided for the
     *         plug-in to be executed, otherwise {@code false}
     */
    private boolean validateProperties() {
        if (!this.properties.containsKey(PROPERTY_OUTPUT_MODE)) {
            logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_MODE);
            return false;
        }

        if (!this.properties.containsKey(PROPERTY_OUTPUT_VIDEO_BACKGROUND)) {
            logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_VIDEO_BACKGROUND);
            return false;
        }

        if (!this.properties.containsKey(PROPERTY_OUTPUT_VIDEO_SECONDS_PER_STORY)) {
            logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_VIDEO_SECONDS_PER_STORY);
            return false;
        }

        String mode = this.properties.get(PROPERTY_OUTPUT_MODE);

        if (mode.equalsIgnoreCase("file")) {
            if (!this.properties.containsKey(PROPERTY_OUTPUT_FILE_LOCATION)) {
                logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_FILE_LOCATION);
                return false;
            }
            if (!this.properties.containsKey(PROPERTY_OUTPUT_FILE_FILENAME)) {
                logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_FILE_FILENAME);
                return false;
            }
        } else if (mode.equalsIgnoreCase("ftp")) {
            if (!this.properties.containsKey(PROPERTY_OUTPUT_FTP_ADDRESS)) {
                logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_FTP_ADDRESS);
                return false;
            }
            if (!this.properties.containsKey(PROPERTY_OUTPUT_FTP_PORT)) {
                logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_FTP_PORT);
                return false;
            }
            if (!this.properties.containsKey(PROPERTY_OUTPUT_FTP_FILENAME)) {
                logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_FTP_FILENAME);
                return false;
            }
        } else {
            logger.log(Level.WARNING, "Invalid value ''{0}'' provided for {1}", new Object[]{mode, PROPERTY_OUTPUT_MODE});
            return false;
        }

        if (!this.properties.containsKey(PROPERTY_OUTPUT_COLLECTION_STATE)) {
            logger.log(Level.WARNING, "{0} property missing", PROPERTY_OUTPUT_COLLECTION_STATE);
            return false;
        }

        return true;
    }
}
